package com.zj.blessings;

import java.util.List;
import android.app.AlertDialog;
//import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
//import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.waps.AppConnect;

import com.activeandroid.ActiveAndroid;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zj.blessings.R;
import com.zj.blessings.adapter.DBItemAdapter;
import com.zj.blessings.db.DBItem;
import com.zj.blessings.db.DBLikeItem;
import com.zj.blessings.db.DBStoreItem;
import com.zj.blessings.util.DBUtils;
import com.zj.blessings.util.LikeDbHelper;
import com.zj.blessings.util.ShareUtils;
import com.zj.blessings.view.CustomProgressDialog;

public class ContentActivity extends ZJActivity implements OnItemClickListener,
		OnItemLongClickListener, OnRefreshListener2<ListView>, OnClickListener {
	private PullToRefreshListView listView;
	private DBItemAdapter myAdapter;
	private String category;
	private CustomProgressDialog mDialog;
	private TextView mTitleTV;
	private Handler handler = new Handler();
	// private AlertDialog mAlertDialog;
	private View mView;
	private TextView backTv;
	private LinearLayout mShowAdLayout;
	private int mPerPageCount = 5;
	private int mIndex = 0;
	private List<DBItem> oldResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mView = LayoutInflater.from(mContext).inflate(R.layout.content_show,
				null);
		setContentView(mView);
		Intent intent = getIntent();
		category = intent.getStringExtra("category");
		mShowAdLayout = (LinearLayout) findViewById(R.id.showAd);
		mTitleTV = (TextView) findViewById(R.id.contentTitle);
		mTitleTV.setText(category);
		backTv = (TextView) findViewById(R.id.contentback);
		backTv.setOnClickListener(this);
		listView = (PullToRefreshListView) findViewById(R.id.list);
		listView.setOnItemLongClickListener(this);
		listView.setOnItemClickListener(this);
		mDialog = CustomProgressDialog.createDialog(this);
		mDialog.setMessage("拼命加载中...");
		mDialog.setCancelable(true);
		myAdapter = new DBItemAdapter(this);
		listView.setAdapter(myAdapter);
		listView.setMode(Mode.PULL_FROM_END);
		listView.setOnRefreshListener(this);
		handler.post(runnable);
		showAds();
		// save();
	}

	private void save() {
		mTitleTV.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showDialog();
			}
		});
		mTitleTV.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						mContext)
						.setTitle("清空初始化数据")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										ActiveAndroid.beginTransaction();
										try {
											List<DBItem> dbItems = DBItem
													.getDBItems(category);
											List<DBStoreItem> dbStoreItems = DBStoreItem
													.getDBStoreItems(category);

											for (int i = 0; i < dbItems.size(); i++) {
												for (int j = 0; j < dbStoreItems
														.size(); j++) {
													if (dbItems.get(i).title
															.equals(dbStoreItems
																	.get(j).title)) {
														dbStoreItems.get(j)
																.delete();
													}
												}
											}
											ActiveAndroid
													.setTransactionSuccessful();
											Toast.makeText(mContext, "数据处理完成！",
													Toast.LENGTH_SHORT).show();
										} finally {
											ActiveAndroid.endTransaction();
										}

									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).create();
				alertDialog.show();
				return true;
			}
		});
	}

	private void showDialog() {
		final EditText editText = new EditText(mContext);
		editText.setWidth(100);
		editText.setHeight(20);
		final AlertDialog alertDialog = new AlertDialog.Builder(this)
				.setTitle("添加初始化数量")
				.setView(editText)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ActiveAndroid.beginTransaction();
						try {
							int count = 10;
							String temp = editText.getText().toString();
							if (!TextUtils.isEmpty(temp)) {
								count = Integer.parseInt(temp);
							}
							List<DBStoreItem> dbStoreItems = DBStoreItem
									.getDBStoreItems(category, count);
							List<DBItem> dbItems = DBItem.getDBItems(category);
							int num = 0;
							for (int i = 0; i < dbStoreItems.size(); i++) {
								if (dbItems != null) {
									boolean isFind = false;
									for (int j = 0; j < dbItems.size(); j++) {
										if (dbStoreItems.get(i).title
												.equals(dbItems.get(j).title)) {
											isFind = true;
											break;
										}
									}
									if (!isFind) {
										DBItem.add(dbStoreItems.get(i));
										num++;
									}
								} else {
									DBItem.add(dbStoreItems.get(i));
									num++;
								}
							}
							ActiveAndroid.setTransactionSuccessful();
							Toast.makeText(mContext, "保存了（" + num + "）条数据",
									Toast.LENGTH_SHORT).show();
						} finally {
							ActiveAndroid.endTransaction();
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		alertDialog.show();

	}

	private void showAds() {
		String value = AppConnect.getInstance(this)
				.getConfig("say_hello", "no");
		if ("no".equals(value)) {
			return;
		}
		AppConnect.getInstance(mContext).showBannerAd(mContext, mShowAdLayout);
		// AppConnect.getInstance(this).showMiniAd(this, mShowAdLayout, 10);//
		// 10秒刷新一次
	}

	private Runnable runnable = new Runnable() {

		@Override
		public void run() {
			new MyAsync().execute(category);
		}
	};

	class MyAsync extends AsyncTask<String, Void, List<DBItem>> {
		@Override
		protected void onPreExecute() {
			listView.setRefreshing();
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected List<DBItem> doInBackground(final String... params) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					ActiveAndroid.beginTransaction();
					try {
						List<DBItem> list = DBItem.getDBItemUnRead(params[0]);
						for (int i = 0; i < list.size(); i++) {
							list.get(i).read = true;
							list.get(i).save();
						}
						ActiveAndroid.setTransactionSuccessful();
					} finally {
						ActiveAndroid.endTransaction();
					}
				}
			}).start();

			List<DBItem> newList = DBItem.getDBItems(params[0], mIndex,
					mPerPageCount);
			try {
				int time = (int) ((Math.random() * 1 + 1) * 500);
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			return newList;
		}

		@Override
		protected void onPostExecute(List<DBItem> result) {

			if (result != null && result.size() > 0) {
				mIndex = mIndex + result.size();
			}

			if (oldResult == null) {
				if (result != null && result.size() > 0) {
					myAdapter.setDBItems(result);
					// Toast.makeText(ContentActivity.this, "加载数据成功！",
					// Toast.LENGTH_SHORT).show();
					oldResult = result;
				} else {
					Toast.makeText(ContentActivity.this, "讨厌，银家还没有准备好！",
							Toast.LENGTH_SHORT).show();
				}
			} else if (oldResult != null) {
				if (result != null && result.size() > 0) {
					myAdapter.addDBItems(result);
					// Toast.makeText(ContentActivity.this, "加载数据成功！",
					// Toast.LENGTH_SHORT).show();
					oldResult = result;
				} else {
					Toast.makeText(ContentActivity.this, "亲！明天再来看看吧！",
							Toast.LENGTH_SHORT).show();
				}
			}
			listView.onRefreshComplete();
			if (mDialog != null && mDialog.isShowing()) {
				mDialog.dismiss();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> arg0) {
		new MyAsync().execute(category);
		mDialog.show();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> arg0) {
		new MyAsync().execute(category);
		mDialog.show();
	}

	@Override
	protected void onPause() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
		handler.removeCallbacks(runnable);
		super.onPause();
	}

	// private void showAlert(final int rId, final String msg) {
	// handler.post(new Runnable() {
	// @Override
	// public void run() {
	// if (!ContentActivity.this.isFinishing()) {
	// if (mAlertDialog == null) {
	// mAlertDialog = new Builder(ContentActivity.this)
	// .setPositiveButton(R.string.ok, null).create();
	// mAlertDialog.setTitle(rId);
	// mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
	// mAlertDialog.setMessage(msg);
	// mAlertDialog.show();
	// } else if (mAlertDialog != null
	// && (!mAlertDialog.isShowing())) {
	// mAlertDialog.setTitle(rId);
	// mAlertDialog.setMessage(msg);
	// mAlertDialog.show();
	// }
	// }
	// }
	// });
	// }

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final Object object = parent.getItemAtPosition(position);
		final Dialog dialog = new Dialog(ContentActivity.this,
				R.style.common_trans_dialog);
		View dialogView = LayoutInflater.from(ContentActivity.this).inflate(
				R.layout.save_like_item_dialog, null);
		dialog.setContentView(dialogView);
		TextView title = (TextView) dialogView
				.findViewById(R.id.saveLikeDialogTitle);
		TextView text = (TextView) dialogView
				.findViewById(R.id.saveLikeDialogText);
		TextView ok = (TextView) dialogView.findViewById(R.id.saveLikeDialogOK);
		ImageView close = (ImageView) dialogView
				.findViewById(R.id.saveLikeDialogClose);
		if (object != null && object instanceof DBItem) {
			DBItem myObject = (DBItem) object;
			if (myObject != null && myObject.title != null
					&& myObject.text != null) {
				title.setText(myObject.title);
				text.setText(myObject.text);
			}
		}
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (object != null && object instanceof DBItem) {
					DBItem myObject = (DBItem) object;
					if (myObject != null && myObject.title != null
							&& myObject.text != null) {
						{
							LikeDbHelper dbHelper = new LikeDbHelper(mContext);
							long num = dbHelper.addLikeItem(myObject);
							if (num > 0) {
								Toast.makeText(ContentActivity.this, "保存成功",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(ContentActivity.this, "保存失败",
										Toast.LENGTH_SHORT).show();
							}
						}
						// DBLikeItem likeItem = new DBLikeItem();
						// likeItem.title = myObject.title;
						// likeItem.text = myObject.text;
						// likeItem.url = myObject.url;
						// likeItem.save_time = System.currentTimeMillis();
						// likeItem.save();
						// Toast.makeText(ContentActivity.this, "保存成功",
						// Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(ContentActivity.this, "保存失败",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(ContentActivity.this, "保存失败",
							Toast.LENGTH_SHORT).show();
				}
				dialog.dismiss();
			}
		});
		dialog.show();
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Object object = parent.getItemAtPosition(position);
		if (object != null) {
			ShareUtils.showShare(mContext, null, false, object);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.contentback:
			finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			break;
		}

	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
	}
}
